<template>
  <div class="spec-preview" @mousemove="mouseMoveHandler">
    <!-- 
      imgUrl的初始值是undefined，所以页面打开的时候图片
      是"裂开的图片"，使用 v-show当imgUrl没有值是不显示图片
    -->
    <img v-show="imgUrl" :src="imgUrl" />
    <div class="event"></div>
    <div class="big">
      <img v-show="imgUrl" :src="imgUrl" ref="bigImg" />
    </div>
    <div class="mask" ref="mask"></div>
  </div>
</template>

<script>
export default {
  name: "Zoom",
  props: ["skuDefaultImg"],
  data() {
    return {
      imgUrl: "",
    };
  },
  watch: {
    /* 
      skuDefaultImg刚开始是undefined,图片不会显示，
      用watch监听它接收到父组件请求的值传递过来后将最新的值赋值给imgUrl    
    */
    skuDefaultImg(newVal) {
      this.imgUrl = newVal;
    },
  },
  mounted() {
    // 挂载的时候绑定一个自定义事件，接收最新的imgUrl
    this.$bus.$on("changeImgUrl", (imgUrl) => {
      // console.log(imgUrl,"imgUrl");
      this.imgUrl = imgUrl;
    });
  },
  methods: {
    //放大镜效果的回调函数
    mouseMoveHandler(e) {
      //获取鼠标到容器的距离
      const toBox = {
        x: e.offsetX,
        y: e.offsetY,
      };
      // 获取鼠标到蒙版边缘的距离(clientWidth:不包括边框  offsetWidth:包括边框 )
      const toMask = {
        x: this.$refs.mask.offsetWidth / 2,
        y: this.$refs.mask.offsetHeight / 2,
      };
      // 得到蒙版移动的距离
      const maskMove = {
        x: toBox.x - toMask.x,
        y: toBox.y - toMask.y,
      };
      //临界值限制
      if (maskMove.x < 0) {
        maskMove.x = 0;
      }
      if (maskMove.x > e.target.clientWidth - this.$refs.mask.offsetWidth) {
        maskMove.x = e.target.clientWidth - this.$refs.mask.offsetWidth;
      }
      if (maskMove.y < 0) {
        maskMove.y = 0;
      }
      if (maskMove.y > e.target.clientHeight - this.$refs.mask.offsetHeight) {
        maskMove.y = e.target.clientHeight - this.$refs.mask.offsetHeight;
      }
      //鼠标移动后蒙版的位置赋值
      this.$refs.mask.style.left = maskMove.x + "px";
      this.$refs.mask.style.top = maskMove.y + "px";

      // 鼠标移动后大图的移动位置
      this.$refs.bigImg.style.left = -maskMove.x * 2 + "px";
      this.$refs.bigImg.style.top = -maskMove.y * 2 + "px";
    },
  },
};
</script>

<style lang="less">
.spec-preview {
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid #ccc;

  img {
    width: 100%;
    height: 100%;
  }

  .event {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 998;
  }

  .mask {
    width: 50%;
    height: 50%;
    background-color: rgba(0, 255, 0, 0.3);
    position: absolute;
    left: 0;
    top: 0;
    display: none;
  }

  .big {
    width: 100%;
    height: 100%;
    position: absolute;
    top: -1px;
    left: 100%;
    border: 1px solid #aaa;
    overflow: hidden;
    z-index: 998;
    display: none;
    background: white;

    img {
      width: 200%;
      max-width: 200%;
      height: 200%;
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  .event:hover ~ .mask,
  .event:hover ~ .big {
    display: block;
  }
}
</style>